/**
 * 轮播
 */
/* eslint-disable react/sort-comp */
/* eslint-disable react/jsx-no-bind */
import { h,Component } from 'preact';
import { random } from '../utils/util.num';
import classNames from 'classnames';
import { mergeClassName } from '../utils/util.obj';

const Item = ({ title, children ,opacity,className,...other }) => (
	<div className={mergeClassName('slide banner-item',className)} style={{ zIndex: 3,  opacity }}>
		 <a title={title} {...other} >
			{children}
		</a>
	</div>
);

const CryLink = ({ index,className,...other }) => <li className={'page '+ className} {...other}>{index}</li>;

class Banner extends Component{

	timer;

	timeUnit = 1000; // 1k毫秒

	constructor(p){
		super(p);
		this.childLength = p.children.length;
		this.state = {
			active: 1
		};
	}

	// 自动播放
	autoPlay = () => {
		if (this.childLength > 1){
			this.timer = setTimeout(i => {
				this.onSelect((this.state.active+1));
				this.autoPlay();
			},this.getRadomTime()*this.timeUnit);
		}
	}

	getRadomTime = () => {
		return random(3,9);
	};

	componentWillUnMount(){
		if (this.timer){
			clearTimeout(this.timer);
		}
	}

	onSelect = _ => {
		if (_ < 0){
			return this.setState({ active: this.childLength-1 });
		}
		if (_ >= this.childLength){
			return this.setState({ active: 0 });
		}
		this.setState({ active: _ });
	}
	
	componentDidMount(){
		this.autoPlay();
	}

	render(props,state) {
		return (
			<div className="banner">
				<div className="fader">
					{props.children.map((child,index) => {
						const childProps = { ...child.props };
						return <Item {...childProps}  opacity={(state.active===index)?1:0} />;
					})}
					<div className="fader_controls">
						<div className="page prev" onClick={_ => this.onSelect(state.active - 1 )} data-target="prev">&#8249;</div>
						<div className="page next" onClick={_ => this.onSelect(state.active + 1 )} data-target="next">&#8250;</div>
						<ul className="pager_list">
							{props.children.map((child,index) => (
								<CryLink
									onClick={_ => this.onSelect(index)}
									className={(state.active===index?'active':'')}
								>
									{index}
								</CryLink>))
							}
						</ul>
					</div>
				</div>
			</div>
		);
	}
}

Banner.Item = Item;

export default Banner;